const moment = require('moment')
const brcypt = require('bcryptjs')
const { sequelize } = require('../core/db')
const { Sequelize, Model } = require('sequelize')
const { USER } = require('../middleware/auth')

class User extends Model {}

User.init(
  {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    uid: {
      type: Sequelize.STRING(32),
      allowNull: false,
      unique: true,
      comment: '加密id'
    },
    username: {
      type: Sequelize.STRING(64),
      allowNull: false,
      comment: '用户名称'
    },
    email: {
      type: Sequelize.STRING(128),
      unique: true,
      allowNull: false,
      comment: '用户邮箱'
    },
    password: {
      type: Sequelize.STRING,
      set(val) {
        // 加密
        const salt = brcypt.genSaltSync(10)
        const pwd = brcypt.hashSync(val, salt)
        this.setDataValue('password', pwd)
      },
      allowNull: false,
      comment: '用户密码'
    },
    scope: {
      type: Sequelize.STRING(10),
      defaultValue: USER,
      allowNull: false,
      comment: '用户权限'
    },
    information: {
      type: Sequelize.STRING(64),
      allowNull: true,
      comment: '个人说明'
    },
    github: {
      type: Sequelize.STRING(128),
      allowNull: true,
      comment: 'github地址'
    },
    web: {
      type: Sequelize.STRING(128),
      allowNull: true,
      comment: '个人网站地址'
    },
    company: {
      type: Sequelize.STRING(32),
      allowNull: true,
      comment: '公司名称'
    },
    cover: {
      type: Sequelize.STRING(128),
      allowNull: true,
      comment: '背景图片'
    },
    portrait: {
      type: Sequelize.STRING(128),
      allowNull: true,
      comment: '头像'
    },
    token: {
      type: Sequelize.STRING(256),
      allowNull: true
    },
    created_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('created_at')).format('YYYY-MM-DD HH:mm')
      }
    },
    updated_at: {
      type: Sequelize.DATE,
      allowNull: false,
      get() {
        return moment(this.getDataValue('updated_at')).format('YYYY-MM-DD HH:mm')
      }
    }
  },
  {
    sequelize,
    modelName: 'user',
    tableName: 'users'
  }
)

module.exports = User
